package com.lbj.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbj.mall.common.utils.PageUtils;
import com.lbj.mall.common.utils.Query;
import com.lbj.mall.product.dao.ProductAttrValueDao;
import com.lbj.mall.product.entity.ProductAttrValueEntity;
import com.lbj.mall.product.service.ProductAttrValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<ProductAttrValueEntity> getBaseListForSpuId(Long spuId) {
        return list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }

    @Transactional
    @Override
    public void updateBySpuId(Long spuId, List<ProductAttrValueEntity> list) {
        // 需要先删除所有的属性才能再次添加
        remove(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        // 重新添加新的属性
        List<ProductAttrValueEntity> collectList = list.stream()
                .peek(item -> item.setSpuId(spuId)).collect(Collectors.toList());
        saveBatch(collectList);
    }

    @Override
    public List<ProductAttrValueEntity> queryFromAttrIds(List<Long> canSearchAttrIdList) {
        return baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>()
                .in("attr_id", canSearchAttrIdList));
    }

}